package com.lixin.smartclassroom.ui.home.tab2.activity

import android.graphics.Color
import android.view.View
import android.view.View.OnClickListener
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.bigkoo.pickerview.listener.OnTimeSelectListener
import com.drake.channel.sendEvent
import com.drake.net.utils.scopeDialog
import com.drake.net.utils.scopeNetLife
import com.lixin.smartclassroom.R
import com.lixin.smartclassroom.api.addsmallzhangjie
import com.lixin.smartclassroom.api.getbigzhangjie
import com.lixin.smartclassroom.api.gettimu
import com.lixin.smartclassroom.api.updatesmallzhangjie
import com.lixin.smartclassroom.bean.BaseBean
import com.lixin.smartclassroom.bean.DataListBean
import com.lixin.smartclassroom.bean.Small
import com.lixin.smartclassroom.databinding.ActivityAddSmallChapterBinding
import com.lixin.smartclassroom.ui.home.adapter.answer
import com.lixinkeji.base.BaseActivity
import com.lixinkeji.extension.getIntentBoolean
import com.lixinkeji.extension.getIntentSerializable
import com.lixinkeji.extension.getIntentString
import com.lixinkeji.extension.gone
import com.lixinkeji.extension.onClick
import com.lixinkeji.extension.start
import com.lixinkeji.extension.text
import com.lixinkeji.extension.toast
import com.lixinkeji.extension.visible
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * Description 添加小节
 * Author: lwc
 * Date:2023/12/8 15:03
 */
class AddSmallChapterAct : BaseActivity<ActivityAddSmallChapterBinding>() {
    override fun getViewBinding() = ActivityAddSmallChapterBinding.inflate(layoutInflater)

    override fun topBarHide() = false
    override fun startPadding() = true
    private var taskType = ""
    private var bigzjid = ""
    private var smallChapterId = ""
    private var questionType = ""
    private var groupMember = 0
    private var mostScore = 0
    private var ifGroup = "2"
    private var ifpingfen = "2"
    private var endTime = ""
    private var pingfen = ""
    private var dataListBean: DataListBean? = null
    private var small: Small? = null
    private var isEdit = false

    override fun title(): String {
        isEdit = getIntentBoolean("isEdit")
        return if (isEdit) "编辑小节"
        else "添加小节"
    }

    override fun iniView() {
        taskType = getIntentString("type")
        bigzjid = getIntentString("bigzjid")

        if (bigzjid.isEmpty()) {
            dataListBean = getIntentSerializable("dataListBean")
        }
        getBigZjData()

        if (isEdit) {

            binding.btnNext.text = "保存"
            small = getIntentSerializable("small")
            if (small?.endtime.toString().isNotEmpty())
                binding.tvCloseTime.text = small?.endtime?.substring(0, 16)
            else
                binding.tvCloseTime.text = "不设置"
            questionType = small?.type!!

        }

        binding.apply {
            if (isEdit) {
                etName.setText(small?.title)
                switchGroup.isChecked = small?.ifgroup == "1"
                if (switchGroup.isChecked) {
                    llAddGroupMember.visible()
                    tvGroup.visible()
                    tvNumGroup.text = small?.peoplecount
                }
                when (small?.type) {
                    "1" -> rgQuestionType.check(R.id.rbNormal)
                    "2" -> rgQuestionType.check(R.id.rbComment)
                    "3" -> rgQuestionType.check(R.id.rbSign)
                }
            }


            if (dataListBean != null) {
                bigzjid = dataListBean!!.id.toString()
                tvChapterName.text = dataListBean?.title

            }
            when (taskType) {
                "3" -> llYanxue.visible()
            }
        }

    }

    private fun getBigZjData() {
        scopeNetLife {
            val baseBean = getbigzhangjie(bigzjid)
            if (baseBean.result == "0") {
                binding.tvChapterName.text = baseBean.name
            }
        }
    }


    override fun onClick() {
        binding.btnChangeTimu.onClick {
            start(SetQuestionAct::class.java) {
                putExtra("questionType", questionType)
                putExtra("smallid", small?.id!!)
            }
        }

        binding.rgQuestionType.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rbNormal -> {
                    questionType = "1"
                }

                R.id.rbComment -> {
                    questionType = "2"
                }

                R.id.rbSign -> {
                    questionType = "3"
                }
            }
        }
        binding.apply {
            btnPlusGroup.onClick {
                groupMember++
                tvNumGroup.text = groupMember.toString()
            }
            btnMinusGroup.onClick {
                groupMember--
                tvNumGroup.text = groupMember.toString()
            }
            btnPlusScore.onClick {
                mostScore++
                tvNumScore.text = mostScore.toString()
            }
            btnMinusScore.onClick {
                mostScore--
                tvNumScore.text = mostScore.toString()
            }




            tvCloseTime.onClick {
                chooseDate(
                    "选择报名截止时间",
                    binding.tvCloseTime.text.toString(),
                    binding.tvCloseTime
                )
            }

            btnNext.onClick {
                if (etName.text().isEmpty()) {
                    toast(etName.hint.toString())
                    return@onClick
                }
                if (tvCloseTime.text == "不设置") {
                    endTime = ""
                } else {
                    endTime = tvCloseTime.text.toString()
                }

                scopeNetLife {
                    when (taskType) {
                        "3" -> {
                            if (tvScore.text.toString() != "请选择最高分") {
                                pingfen = tvScore.text.toString()
                            }
                            if (isEdit) {
                                val baseBean = updatesmallzhangjie(
                                    small?.id!!,
                                    etName.text(),
                                    endTime,
                                    ifGroup,
                                    leixing = questionType,
                                    peoplecount = tvNumGroup.text.toString()

                                )
                                goSetQuestion(baseBean)

                            } else {
                                val baseBean = addsmallzhangjie(
                                    bigzjid,
                                    etName.text(),
                                    endTime,
                                    ifGroup,
                                    tvNumGroup.text.toString(),
                                    questionType,
                                    ifpingfen,
                                    pingfen
                                )
                                goSetQuestion(baseBean)
                            }

                        }

                        else -> {
                            if (isEdit) {
                                val baseBean = updatesmallzhangjie(
                                    small?.id!!,
                                    etName.text(),
                                    endTime,
                                    ifGroup,
                                    type = questionType,
                                    peoplecount = tvNumGroup.text.toString()

                                )
                                goSetQuestion(baseBean)
                            } else {
                                val baseBean = addsmallzhangjie(
                                    bigzjid,
                                    etName.text(),
                                    endTime,
                                    ifGroup,
                                    tvNumGroup.text.toString(),
                                    questionType
                                )
                                goSetQuestion(baseBean)
                            }


                        }
                    }

                }
            }

            switchGroup.setOnCheckedChangeListener { _, isChecked ->
                ifGroup = if (isChecked) {
                    llAddGroupMember.visible()
                    tvGroup.visible()
                    "1"
                } else {
                    llAddGroupMember.gone()
                    tvGroup.gone()
                    "2"
                }
            }
            switchScore.setOnCheckedChangeListener { _, isChecked ->
                ifpingfen = if (isChecked) {
                    llOpenScore.visible()
                    tvScore.visible()
                    "1"
                } else {
                    llOpenScore.visible()
                    tvScore.visible()
                    "2"
                }
            }
        }
    }

    private fun goSetQuestion(baseBean: BaseBean) {
        if (baseBean.result == "0") {
            sendEvent("cs", "refreshDaGang")
            if (questionType == "3") {
                finish()
            } else if (questionType == "2") {
                if (isEdit) {
                    finish()
                } else {
                    start(SetEvaluateQuestionAct::class.java) {
                        putExtra("smallid", baseBean.id)
                    }
                    finish()
                }

            } else {
                if (isEdit) {
                    finish()
                } else {
                    start(SetQuestionAct::class.java) {
                        putExtra("questionType", questionType)
                        putExtra("smallid", baseBean.id)
                    }
                    finish()
                }

            }
        }
    }


    private fun chooseDate(title: String, def: String, view: TextView) {
        val format = "yyyy-MM-dd HH:mm"
        val selectedDate = Calendar.getInstance()
        if (def.isNotEmpty() && def != "不设置") {
            val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
            selectedDate.time = df.parse(def)
        }


        val mDatePickerView = TimePickerBuilder(this, object : OnTimeSelectListener {
            override fun onTimeSelect(date: Date?, v: View?) {
                val df: DateFormat = SimpleDateFormat(format, Locale.getDefault())
                val time = df.format(date)
                view.text = time
            }
        })
        mDatePickerView.addOnCancelClickListener(object : OnClickListener {
            override fun onClick(v: View?) {
                view.text = "不设置"
            }
        })
        val mDatePickerViewBuilder =
            mDatePickerView.setType(booleanArrayOf(true, true, true, true, true, false))// 默认全部显示
                .setCancelText("不设置")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(16)//滚轮文字大小
                .setTitleSize(15)//标题文字大小
                .setTitleText(title)//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(false)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(ContextCompat.getColor(this, R.color.color_blue_44))//确定按钮文字颜色
                .setCancelColor(ContextCompat.getColor(this, R.color.color_blue_44))//取消按钮文字颜色
                .setTitleColor(ContextCompat.getColor(this, R.color.color_black_33))
                .setTitleBgColor(Color.WHITE)//标题背景颜色
                .setBgColor(Color.WHITE)//滚轮背景颜色
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setLineSpacingMultiplier(2.5f)
                .setLabel("", "", "", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build()

        if (!mDatePickerViewBuilder.isShowing) mDatePickerViewBuilder.show()

    }


}